import { loginApi, getUserInfoApi } from '@/api/user'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {}
    }
  },
  mutations: {
    // 1. 存token
    SET_TOKEN(state, token) {
      // 1.1 往本地存储token
      setToken(token)
      // 1.2 往state中存储token
      state.token = token
    },
    // 2. 删除token
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    // 3. 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    // 4.清空用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 1. 登录
    async doLogin(context, { username, password }) {
      // 1.1调用登录接口
      const { token } = await loginApi({ username, password })
      context.commit('SET_TOKEN', token)
      Message.success('登陆成功~')
      // 1.2跳转倒首页·
      router.replace('/dashboard')
    },
    // 2.退出登录
    logout(context) {
      context.commit('REMOVE_TOKEN')
      context.commit('CLEAR_USER_INFO')
      // todo
    },
    // 3.获取用户信息
    async getUserInfo(context) {
      const userInfo = await getUserInfoApi()
      context.commit('SET_USER_INFO', userInfo)
      // console.log(userInfo)
    }

  }
}
